package web.panels;

import application.authorization.MyRoles;
import domain.cms.CmsPage;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.user.CmsUserService;
import web.commons.CmsLink;
import web.commons.SecureLink;
import web.eshop.MultipleProductsEshopPage;
import web.eshop.wizard.RegisteredWizardPage;
import web.eshop.wizard.UnregisteredWizardPage;

import java.util.List;

public final class TopMenuPanel extends Panel {

    @SpringBean
    private CmsUserService cmsUserService;


    public TopMenuPanel(String id) {
        this(id, null);

    }

    public TopMenuPanel(String id, Long sectionId) {
        super(id);
        SectionsLdmModel sectionsModel = new SectionsLdmModel();
        SectionListView sectionListView = new SectionListView("section", sectionsModel, sectionId);

        add(sectionListView);

        add(new SecureLink("eshop", MultipleProductsEshopPage.class, RENDER, MyRoles.USERS));
        add(new BookmarkablePageLink("unregWizard", UnregisteredWizardPage.class));
        add(new SecureLink("wizard2", RegisteredWizardPage.class, RENDER, MyRoles.USERS));
    }

    class SectionsLdmModel extends LoadableDetachableModel<List<CmsPage>> {

        @Override
        protected List<CmsPage> load() {
            return cmsUserService.getSections();
        }
    }

    class SectionListView extends ListView<CmsPage> {

        Long choosedSectionId;

        public SectionListView(String id, IModel<? extends List<? extends CmsPage>> model, Long choosedSectionId) {
            super(id, model);
            this.choosedSectionId = choosedSectionId;
        }

        @Override
        protected void populateItem(final ListItem<CmsPage> item) {
            item.add(new CmsLink("link", item.getModelObject()));
            if (item.getModelObject().getId().equals(choosedSectionId)) {
                item.add(new SimpleAttributeModifier("class", "selected"));
            }
        }
    }
}
